<template>
  <div>
    <!-- 面包屑导航器 -->
    <el-breadcrumb separator="/">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item><a href="/">商品管理</a></el-breadcrumb-item>
      <el-breadcrumb-item>参数列表</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- 卡片视图区-->
    <el-card>
      <!--头部警告区-->
      <el-alert show-icon :closable="false" title="注意: 只允许为第三级分类设置相关参数" type="warning"></el-alert>
      <!-- 选择商品分类区-->
      <el-row class="cat_opt">
         <el-col>
            <span>选择商品分类: </span>
            <!--级联选择框-->
            <el-cascader
             expand-trigger="hover"
             v-model="selectedKeys"
             :options="CateList"
             :props="cascaderProps"
             @change="CateChanged" clearable  change-on-select>
            </el-cascader>
         </el-col>
      </el-row>
      <!-- 页签区域-->
      <el-tabs v-model="activeName" @tab-click="handleTabClick">
        <!--页面1-->
        <el-tab-pane label="动态参数" name="many">
           <el-button @click="addDialogVisible = true" type="primary" size="mini" :disabled="isOpen">添加参数</el-button>
           <!--动态参数表格-->
           <el-table :data="manyTableData" border stripe>
              <!--展开行-->
              <el-table-column type="expand">
                 <template slot-scope="scope">
                    <!--属性参数的标签-->
                    <el-tag @close="handleClose(i,scope.row)" class="attr_vals" v-for="(item, i) in scope.row.attr_vals" :key="i" closable>{{item}}</el-tag>
                    <!--自定义添加Tag标签-->
                    <el-input
                     class="input-new-tag"
                     v-if="scope.row.inputVisible"
                     v-model="scope.row.inputValue"
                     ref="saveTagInput"
                     size="small"
                     @keyup.enter.native="handleInputConfirm(scope.row)"
                     @blur="handleInputConfirm(scope.row)"
                    >
                    </el-input>
                    <el-button v-else class="button-new-tag" size="small" @click="showInput(scope.row)">+ New Tag</el-button>
                 </template>
              </el-table-column>
              <!--索引列-->
              <el-table-column type="index"></el-table-column>
              <el-table-column label="参数名称" prop="attr_name"></el-table-column>
              <el-table-column label="操作">
                 <template slot-scope="scope" >
                    <el-button type="primary" @click="showEditDialog(scope.row.attr_id)" size="mini" icon="el-icon-edit">编辑</el-button>
                    <el-button type="danger" @click="removeParams(scope.row.attr_id)"   size="mini" icon="el-icon-delete">删除</el-button>
                 </template>
              </el-table-column>
           </el-table>
        </el-tab-pane>
        <!--页面2-->
        <el-tab-pane label="静态属性" name="only">
           <el-button @click="addDialogVisible = true" type="primary" size="mini" :disabled="isOpen">添加属性</el-button>
           <!--静态属性表格-->
           <el-table :data="onlyTableData" border stripe>
            <!--展开行-->
            <el-table-column type="expand">
              <template slot-scope="scope">
                <!--属性参数的标签-->
                <el-tag @close="handleClose(i,scope.row)" class="attr_vals" v-for="(item, i) in scope.row.attr_vals" :key="i" closable>{{item}}</el-tag>
                <!--自定义添加Tag标签-->
                <el-input
                  class="input-new-tag"
                  v-if="scope.row.inputVisible"
                  v-model="scope.row.inputValue"
                  ref="saveTagInput"
                  size="small"
                  @keyup.enter.native="handleInputConfirm(scope.row)"
                  @blur="handleInputConfirm(scope.row)"
                >
                </el-input>
                <el-button v-else class="button-new-tag" size="small" @click="showInput(scope.row)">+ New Tag</el-button>
              </template>
            </el-table-column>
            <!--索引列-->
            <el-table-column type="index"></el-table-column>
            <el-table-column label="属性名称" prop="attr_name"></el-table-column>
            <el-table-column label="操作">
              <template  slot-scope="scope" >
                <el-button type="primary" @click="showEditDialog(scope.row.attr_id)" size="mini" icon="el-icon-edit">编辑</el-button>
                <el-button type="danger" @click="removeParams(scope.row.attr_id)" size="mini" icon="el-icon-delete">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
      </el-tabs>
    </el-card>

    <!-- 动态参数和静态属性的对话框-->
    <el-dialog
      :title="titleText"
      :visible.sync="addDialogVisible"
      width="50%"
      @close="addDialogClosed">
      <!--内容主体区域-->
      <el-form :model="addForm" :rules="addFormRules" ref="addFormRef" label-width="80px">
        <el-form-item :label="titleText" prop="attr_name" >
          <el-input v-model="addForm.attr_name" ></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
          <!--内容底部按钮区域 点击了就隐藏对话框-->
        <el-button @click="addDialogVisible = false">取 消</el-button>
        <el-button  @click="addParams" type="primary">确 定</el-button>
        </span>
    </el-dialog>
    <!-- 修改参数对话框对话框-->
    <el-dialog
      :title="'修改' + titleText"
      :visible.sync="editDialogVisible"
      width="50%"
      @close="editDialogClosed">
      <!--内容主体区域-->
      <el-form :model="editForm" :rules="editFormRules" ref="editFormRef" label-width="80px">
        <el-form-item :label="titleText" prop="attr_name" >
          <el-input v-model="editForm.attr_name" ></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
          <!--内容底部按钮区域 点击了就隐藏对话框-->
        <el-button @click="editDialogVisible = false">取 消</el-button>
        <el-button  @click="editParams" type="primary">确 定</el-button>
        </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data () {
    return {
      // 商品分类列表
      CateList: [],
      // 配置级联选择框
      cascaderProps: {
        value: 'cat_id',
        label: 'cat_name',
        children: 'children'
      },
      // 动态参数的数据
      manyTableData: [],
      // 静态属性的数据
      onlyTableData: [],
      // 被激活页签名称
      activeName: 'many',
      // 控制按钮与文本框的显示
      inputVisible: false,
      inputValue: '',
      // 级联选择框所选择的数据
      selectedKeys: [],
      // 控制按钮开关
      isOpen: true,
      addDialogVisible: false,
      editDialogVisible: false,
      addForm: {
        attr_name: ''
      },
      editForm: {},
      addFormRules: {
        attr_name: [
          { required: true, message: '请输入参数', trigger: 'blur' }
        ]
      },
      editFormRules: {
        attr_name: [
          { required: true, message: '请输入参数', trigger: 'blur' }
        ]
      }
    }
  },
  created () {
    this.getCateList()
  },
  methods: {
    async getCateList () {
      const { data: res } = await this.$http.get('categories')
      if (res.meta.status !== 200) return this.$message.error('获取商品分类失败')
      this.CateList = res.data
    },
    // 级联选择框变化触发 获取所有商品参数
    async CateChanged () {
      // 判断是否选择了三级分类
      if (this.selectedKeys.length !== 3) {
        this.selectedKeys = []
        this.isOpen = true
        // 清空参数列表
        this.manyTableData = []
        this.onlyTableData = []
        return
      }
      this.isOpen = false
      // 根据所选分类的id和所处面板获取对应参数
      const { data: res } = await this.$http.get(`categories/${this.cateId}/attributes`, {
        params: { sel: this.activeName }
      })

      res.data.forEach(item => {
        item.attr_vals = item.attr_vals ? item.attr_vals.split(',') : []
        // 控制文本框的显示与隐藏
        item.inputVisible = false
        item.inputValue = ''
      })
      if (res.meta.status !== 200) return this.$message.error('获取参数列表失败')
      if (this.activeName === 'many') {
        this.manyTableData = res.data
      } else {
        this.onlyTableData = res.data
      }
    },
    // Tab更换激活状态
    handleTabClick () {
      this.CateChanged()
    },
    // 清空表单
    addDialogClosed () {
      this.$refs.addFormRef.resetFields()
    },
    editDialogClosed () {
      this.$refs.editFormRef.resetFields()
    },
    // 添加参数
    addParams () {
      this.$refs.addFormRef.validate(async valid => {
        if (!valid) return
        const { data: res } = await this.$http.post(`categories/${this.cateId}/attributes`, {
          attr_name: this.addForm.attr_name,
          attr_sel: this.activeName
        })
        if (res.meta.status !== 201) return this.$message.error('添加参数失败')
        this.$message.success('添加参数成功')
        this.addDialogVisible = false
        this.CateChanged()
      })
    },
    // 修改编辑参数
    editParams () {
      this.$refs.editFormRef.validate(async valid => {
        if (!valid) return
        console.log(this.cateId)
        console.log(this.editForm.attr_id)
        console.log(this.editForm.attr_name)
        console.log(this.activeName)
        const { data: res } = await this.$http.put(`categories/${this.cateId}/
          attributes/${this.editForm.attr_id}`, {
          attr_name: this.editForm.attr_name,
          attr_sel: this.activeName
        })
        if (res.meta.status !== 200) return this.$message.error('修改参数失败')
        this.$message.success('修改参数成功')
        this.getCateList()
        this.editDialogVisible = false
      })
    },
    async showEditDialog (id) {
      const { data: res } = await this.$http.get(`categories/${this.cateId}/attributes/${id}`, {
        attr_sel: this.activeName
      })
      if (res.meta.status !== 200) return this.$message.error('获取参数信息失败')
      this.editForm = res.data
      this.editDialogVisible = true
    },
    // 删除参数
    async removeParams (id) {
      // 弹对话框
      const confirmResult = await this.$confirm('此操作将永久删除该商品参数, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(err => {
        return err
      })
      // 用户点删除 返回confirm  点击取消返回 cancel
      if (confirmResult !== 'confirm') {
        return this.$message.info('已经取消删除')
      }
      // 删除操作
      const { data: res } = await this.$http.delete(`categories/${this.cateId}/attributes/${id}`)
      if (res.meta.status !== 200) return this.$message.error('删除商品参数失败')
      console.log(res)
      this.$message.success('删除商品参数成功')
      this.CateChanged()
    },
    // 文本框失去焦点或者摁下enter触发
    async handleInputConfirm (row) {
      // 切换为buttom
      if (row.inputValue.trim().length === 0) {
        row.inputValue = ''
        row.inputVisible = false
        return
      }
      // 添加Tag
      row.attr_vals.push(row.inputValue.trim())
      row.inputValue = ''
      row.inputVisible = false
      // 发起请求保存到数据库中
      const { data: res } = await this.$http.put(`categories/${this.cateId}/attributes/${row.attr_id}`, {
        attr_name: row.attr_name,
        attr_sel: row.attr_sel,
        attr_vals: row.attr_vals.join(' ')
      })
      if (res.meta.status !== 200) this.$message.error('添加标签失败')
      this.$message.success('添加标签成功')
    },
    // 展示输入框 添加tag标签
    showInput (row) {
      row.inputVisible = true
      // 自动获取焦点 $nextTick作用当页面上元素被重新渲染之后才会执行回调函数中的代码
      this.$nextTick(_ => {
        this.$refs.saveTagInput.$refs.input.focus()
      })
    },
    // 删除标签
    async handleClose (i, row) {
      row.attr_vals.splice(i, 1)
      // 发起请求保存到数据库中
      const { data: res } = await this.$http.put(`categories/${this.cateId}/attributes/${row.attr_id}`, {
        attr_name: row.attr_name,
        attr_sel: row.attr_sel,
        attr_vals: row.attr_vals.join(' ')
      })
      if (res.meta.status !== 200) this.$message.error('删除标签失败')
      this.$message.success('删除标签成功')
    }
  },
  computed: {
    // 当前选中的id
    cateId () {
      if (this.selectedKeys.length === 3) return this.selectedKeys[2]
      return null
    },
    // 当前title
    titleText () {
      if (this.activeName === 'many') {
        return '动态参数'
      } else {
        return '静态属性'
      }
    }
  }
}
</script>

<style scoped>
  .cat_opt{
    margin:15px 0px
  }
  .attr_vals{
     margin-left: 10px;
  }
  .input-new-tag{
    width: 120px;
  }
  .button-new-tag{
    margin-left: 10px;
  }
</style>
